﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using DCT.ViewModel;

namespace DCT.View
{
    public class MoveThumb : Thumb
    {
        private DeviceBaseView _deviceBaseView;
        private RotateTransform _rotateTransform;
        private DeviceMapViewModel _deviceMapViewModel;
        private PackageCommand _packageCommand;

        public MoveThumb()
        {
            DragStarted += new DragStartedEventHandler(this.MoveThumb_DragStarted);
            DragDelta += new DragDeltaEventHandler(this.MoveThumb_DragDelta);
            DragCompleted += new DragCompletedEventHandler(MoveThumb_DragCompleted);
        }

        private void MoveThumb_DragStarted(object sender, DragStartedEventArgs e)
        {
            _deviceBaseView = sender as DeviceBaseView;
            _deviceMapViewModel = _deviceBaseView.DeviceViewModel.DeviceMapViewModel;
            _rotateTransform = _deviceBaseView.RenderTransform as RotateTransform;

            e.Handled = true;
        }

        private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            if (_deviceMapViewModel != null)
            {
                if (_packageCommand == null)
                {
                    _packageCommand = new PackageCommand();
                    _deviceMapViewModel.UndoRedo.InsertInUnDoRedoForPackage(_packageCommand);
                }
                
                Point offset = this._rotateTransform.Transform(
                new Point(e.HorizontalChange, e.VerticalChange));

                if (this._deviceMapViewModel.Move_Can(offset))
                {
                    this._deviceMapViewModel.Move_Execute(offset);
                }
            }
            
            e.Handled = true;
        }

        private void MoveThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            if (_packageCommand != null)
            {
                _deviceMapViewModel.UndoRedo.InsertInUnDoRedoForPackage(_packageCommand.AnotherPackageCommand);
                _packageCommand = null;
            }

            e.Handled = true;
        }
    }
}
